package com.asset.dispoal.file.clouddesk.service.command;

import com.asset.dispoal.file.clouddesk.dto.CloudDeskQueryRequest;
import com.asset.dispoal.file.clouddesk.dto.CloudDeskQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class CloudDeskQueryCommand implements BaseCommand<CloudDeskQueryRequest, Result<List<CloudDeskQueryResponse>>> {

    @Autowired
    private Environment environment;

    @Override
    public Result<List<CloudDeskQueryResponse>> execute(CloudDeskQueryRequest request) {
        String headUrl = environment.getProperty("file.evidence.url");
        String cloudDeskFolder = environment.getProperty("file.cloudDesk.url");
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append(headUrl)
                .append(File.separator)
                .append(cloudDeskFolder)
                .append(File.separator)
                .append(request.getAssetInstBatchId())
                .append(File.separator);
        if (StringUtil.isNotEmpty(request.getDirName())) {
            strBuilder.append(request.getDirName());
        }
        List<CloudDeskQueryResponse> responseList = new ArrayList<>();
        File file = new File(strBuilder.toString());
        if (!file.exists()) {
            return Result.ok(responseList);
        }
        File[] queryFiles = file.listFiles();
        if (queryFiles != null) {
            for (File queryFile : queryFiles) {
                StringBuilder downloadBuilder = new StringBuilder();
                downloadBuilder.append(strBuilder);
                CloudDeskQueryResponse response = new CloudDeskQueryResponse();
                response.setFileName(queryFile.getName());
                response.setDownloadFileName(downloadBuilder.append(queryFile.getName()).toString().replace(headUrl, ""));
                if (queryFile.isDirectory()) {
                    response.setUseDir("1");
                } else {
                    response.setUseDir("0");
                }
                responseList.add(response);
            }
        }

        return Result.ok(responseList);
    }
}
